<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="支付方式" prop="payType">
        <el-select
          v-model="queryParams.payType"
          placeholder="请选择支付方式"
          clearable
          popper-append-to-body
        >
          <el-option
            v-for="item in payTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          popper-append-to-body
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="!isSingleSelected"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="!isMultipleSelected"
          @click="handleBatchDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 订单表格 -->
    <el-table
      v-loading="loading"
      :data="orderList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      :header-cell-style="{ 'text-align': 'center', 'width': 'calc(100% / 6)' }"
      :cell-style="{ 'text-align': 'center', 'width': 'calc(100% / 6)' }"
    >
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="left" prop="id" />-->
      <el-table-column label="用户昵称" align="left" prop="userName" />
      <el-table-column label="代金券名字" align="left" prop="voucherName" />

      <el-table-column label="支付方式" align="left">
        <template #default="scope">
          <el-tag :type="getPayTypeTagType(scope.row.payType)">{{ getPayTypeLabel(scope.row.payType) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="订单状态" align="left">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="支付时间" align="left" prop="payTime">
        <template #default="scope">
          {{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="下单用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入下单用户ID" />
        </el-form-item>
        <el-form-item label="代金券ID" prop="voucherId">
          <el-input v-model="form.voucherId" placeholder="请输入购买的代金券ID" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payType">
          <el-select
            v-model="form.payType"
            placeholder="请选择支付方式"
            clearable
            popper-append-to-body
          >
            <el-option
              v-for="item in payTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择订单状态"
            clearable
            popper-append-to-body
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付时间" prop="payTime">
          <el-date-picker
            clearable
            v-model="form.payTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择支付时间"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order";


export default {
  name: "Order",
  data() {
    return {
      loading: false,
      selectedRows: [],
      isSingleSelected: false,
      isMultipleSelected: false,
      showSearch: true,
      total: 0,
      orderList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        voucherId: null,
        payType: null,
        status: null,
      },
      form: {
        id: null,
        userId: null,
        voucherId: null,
        payType: null,
        status: null,
        payTime: null,
      },
      rules: {
        userId: [{ required: true, message: "下单用户ID不能为空", trigger: "blur" }],
        voucherId: [{ required: true, message: "代金券ID不能为空", trigger: "blur" }],
        payType: [{ required: true, message: "支付方式不能为空", trigger: "change" }],
        status: [{ required: true, message: "订单状态不能为空", trigger: "change" }],
        payTime: [{ required: true, message: "支付时间不能为空", trigger: "blur" }],
      },
      payTypeOptions: [
        { value: 1, label: "余额支付" },
        { value: 2, label: "支付宝" },
        { value: 3, label: "微信" },
      ],
      statusOptions: [
        { value: 1, label: "未支付" },
        { value: 2, label: "已支付" },
        { value: 3, label: "已核销" },
        { value: 4, label: "已取消" },
        { value: 5, label: "退款中" },
        { value: 6, label: "已退款" },
      ],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取订单列表
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(({ rows, total }) => {
        this.orderList = rows;
        this.total = total;
        this.loading = false;
      });
    },

    // 取消操作
    cancel() {
      this.open = false;
      this.resetForm();
    },

    // 重置表单
    resetForm() {
      this.form = {
        id: null,
        userId: null,
        voucherId: null,
        payType: null,
        status: null,
        payTime: null,
      };
      this.$refs.formRef && this.$refs.formRef.resetFields();
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询条件
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    // 选中行变更
    handleSelectionChange(rows) {
      this.selectedRows = rows;
      this.isSingleSelected = rows.length === 1;
      this.isMultipleSelected = rows.length > 0;
    },

    // 新增订单
    handleAdd() {
      this.resetForm();
      this.open = true;
      this.title = "新增订单";
    },

    // 修改订单
    handleUpdate(row) {
      this.resetForm();
      const id = row.id;
      getOrder(id).then(({ data }) => {
        this.form = { ...data };
        this.open = true;
        this.title = "修改订单";
      });
    },

    // 单行删除
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm(`确认删除ID为 ${id} 的订单？`).then(() => {
        return delOrder(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      });
    },

    // 批量删除
    handleBatchDelete() {
      const ids = this.selectedRows.map((row) => row.id);
      if (!ids.length) return this.$modal.msgWarning("请选择要删除的订单");

      this.$modal.confirm(`确认删除选中的 ${ids.length} 条订单？`).then(() => {
        return delOrder(ids.join(","));
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(`成功删除 ${ids.length} 条数据`);
      });
    },

    // 获取支付方式标签
    getPayTypeLabel(value) {
      return this.payTypeOptions.find((item) => item.value === Number(value))?.label || '未知';
    },

    // 获取订单状态标签
    getStatusLabel(value) {
      return this.statusOptions.find((item) => item.value === Number(value))?.label || '未知';
    },

    // 获取支付方式标签类型
    getPayTypeTagType(value) {
      switch (Number(value)) {
        case 1:
          return 'info';
        case 2:
          return 'primary';
        case 3:
          return 'success';
        default:
          return 'default';
      }
    },

    // 获取订单状态标签类型
    getStatusTagType(value) {
      switch (Number(value)) {
        case 1:
          return 'info';
        case 2:
          return 'success';
        case 3:
          return 'primary';
        case 4:
          return 'danger';
        case 5:
          return 'warning';
        case 6:
          return 'danger';
        default:
          return 'default';
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (!valid) return;

        const api = this.form.id ? updateOrder : addOrder;
        api(this.form).then(() => {
          this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        });
      });
    },

    // 导出
    handleExport() {
      this.download('system/order/export', this.queryParams, `order_${Date.now()}.xlsx`);
    }
  }
}
</script>
